package chlibproxy;

import aspect.MyAspect;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;



//cglib动态代理
public class CglibProxyFactory {
    public static  Object getCjLibProxy(Object targetClass){

        Object object= Enhancer.create(targetClass.getClass(),



                //,new InvocationHandler() {
//                    @Override
//                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                        //前置增强
//                MyAspect myAspect = new MyAspect();
//                myAspect.beforeLog();
//                //目标方法
//                Object invoke = method.invoke(targetClass, args);
//                myAspect.afterLog();
//                return invoke;
//                    }
//                }
                        new MethodInterceptor(){
                            @Override
                            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                                //前置增强
                                MyAspect myAspect = new MyAspect();
                                myAspect.beforeLog();
                                //目标方法
                                Object invoke = proxy.invokeSuper(obj, args);
                                myAspect.afterLog();
                                return invoke;
                            }
                    }
        );
        return object;
    }
}
